local jizhaoq = fk.CreateSkill {
  name = "jizhaoq",
}

jizhaoq:addEffect(fk.EventPhaseStart, {
  anim_type = "control",
  events = { fk.EventPhaseStart },
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) and (player.phase == Player.Start or player.phase == Player.Finish)
  end,
  on_cost = function(self, event, target, player, data)
    local room = player.room
    local targets = table.filter(room.alive_players, function(p)
      return not p:isKongcheng() or table.find(room.alive_players, function(to)
        return p:canMoveCardsInBoardTo(to, nil)
      end) ~= nil
    end)
    if #targets == 0 then return end
    local to = room:askToChoosePlayers(player,
      { targets = targets, min_num = 1, max_num = 1, prompt = "#jizhaoq-choose", skill_name = self.name, cancelable = true })
    if #to > 0 then
      event:setCostData(self, { tos = to })
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local to = event:getCostData(self).tos[1]
    local use = nil
    if not to:isKongcheng() then
      use = room:askToUseRealCard(to,
        {
          pattern = to:getCardIds("h"),
          skill_name = self.name,
          prompt = "#jizhaoq-use:" .. player.id,
          extra_data = {
            bypass_times = true,
            extraUse = true,
          },
          cancelable = true,
          skip = true
        })
    end
    if use then
      room:useCard(use)
    else
      local choices = {}
      if not to:isKongcheng() then table.insert(choices, "jizhaoq_hand") end
      local targets = table.filter(room.alive_players, function(p) return to:canMoveCardsInBoardTo(p, nil) end)
      if #targets > 0 then table.insert(choices, "jizhaoq_board") end
      if #choices == 0 then return end
      local choice = room:askToChoice(player, { choices = choices, skill_name = self.name })
      if choice == "jizhaoq_hand" then targets = room:getOtherPlayers(to) end
      local t = room:askToChoosePlayers(player,
      { targets = table.map(targets, Util.IdMapper), min_num = 1, max_num = 1, prompt = "#jizhaoq-move::" .. to.id, skill_name =
      self.name, cancelable = true })
      if #t > 0 then
        if choice == "jizhaoq_hand" then
          local cid = room:askToChooseCard(player,{target=to,flag="h",skill_name=self.name})
          room:moveCardTo(cid, Player.Hand, t[1], fk.ReasonJustMove, self.name, nil, false, player)
        else
          room:askToMoveCardInBoard(player,{target_one=to,target_two=t[1],skill_name=self.name,move_from=to,exclude_ids={}})
        end
      end
    end
  end,
})

return jizhaoq
